package com.authsphere.security.authorization;

import com.authsphere.security.common.ResponseCode;
import com.authsphere.security.common.TokenErrorAuthenticationToken;
import com.authsphere.security.common.TokenExpiredAuthenticationToken;
import com.authsphere.security.common.TokenNotExistedAuthenticationToken;
import com.authsphere.security.common.handler.AbstractResponseAuthenticationSuccessHandler;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/13 11:21
 **/
public class AuthSphereResponseAuthenticationSuccessHandler extends AbstractResponseAuthenticationSuccessHandler {
    @Override
    protected Object extract(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        AuthSphereResponse.Builder builder = AuthSphereResponse.Builder
                .builder();
        ResponseCode responseCode = ResponseCode.SUCCESS;
        if (authentication instanceof TokenNotExistedAuthenticationToken) {
            responseCode = ResponseCode.TOKEN_NOT_FOUND;
        } else if (authentication instanceof TokenExpiredAuthenticationToken) {
            responseCode = ResponseCode.TOKEN_EXPIRED;
        } else if (authentication instanceof TokenErrorAuthenticationToken) {
            responseCode = ResponseCode.TOKEN_ERROR;
        }
        builder.code(responseCode.getCodeValue())
                .message(responseCode.getMessage());
        if (responseCode == ResponseCode.SUCCESS) {
            AuthorizationAuthenticationToken authorizationAuthenticationToken = (AuthorizationAuthenticationToken) authentication;
            builder.success(true)
                    .accessToken(authorizationAuthenticationToken.getPrincipal())
                    .principal(authorizationAuthenticationToken.getStoredAuthentication().getPrincipal());
        }
        return builder.build();
    }
}
